//
//  InvitingFriendsViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/8/17.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "InvitingFriendsViewController.h"
#import "InvitingListViewController.h"
#import "CheckVersionAlearView.h"
@interface InvitingFriendsViewController ()

@end

@implementation InvitingFriendsViewController
- (void)viewWillAppear:(BOOL)animated
{
    [self SetnavigationBarBackgroundImage:MAINBLACKCOLOR Alpha:0];
     [self statusBarStyleIsDark:NO];
    [super viewWillDisappear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [self SetnavigationBarBackgroundImage:MAINBLACKCOLOR Alpha:1];
    [super viewWillDisappear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title =@"";
    self.navigationItem.leftBarButtonItem  = [UIBarButtonItem LeftitemWithImageNamed:@"title-back" title:nil target:self action:@selector(returnVC)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem RightitemWithImageNamed:@"" title:Localized(@"Invitation_record") target:self action:@selector(invitingList)];
    [self initUI];
    [self getrecommend];
    [self.view addSubview:self.firestQrcodeImage];
}
- (void)initUI
{
    
    self.invitingCodeLable.text = Localized(@"Invitation_code");
    self.copylable.text = Localized(@"Invitation_message");
    [self.button setTitle:Localized(@"Invitation_copy_code") forState:0];
    self.button.titleLabel.adjustsFontSizeToFitWidth = YES;
     _bgView.hidden = YES;
    KViewRadius(_button, _button.height/2);
    KViewRadius(_bgView, 15);
    _button.backgroundColor = TABTITLECOLOR;
    _invitingCode.textColor = TABTITLECOLOR;
    //1.创建长按手势
    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imglongTapClick:)];
    
    //2.开启人机交互
    self.bgView.userInteractionEnabled = YES;
    
    //3.添加手势
    [self.bgView addGestureRecognizer:longTap];
    
    //1.创建长按手势
    UILongPressGestureRecognizer *longTap1 = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imglongTapClick1:)];
    
    //2.开启人机交互
    self.bgImageVIew.userInteractionEnabled = YES;
    
    //3.添加手势
    [self.bgImageVIew addGestureRecognizer:longTap1];
    
    
}
- (void)getrecommend
{
    [self showLoadingAnimation];
  
    WeakSelf
    [self GETWithHost:@"" path:recommend param:@{} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self stopLoadingAnimation];
        if ([responseObject[@"code"] integerValue]==0)//成功
        {
            NSArray * urlArray = responseObject[@"result"][@"links"];
            weakSelf.invitingCode.text = responseObject[@"result"][@"invite_code"];
            NSString * imageUrl = responseObject[@"result"][@"image"][@"image"];
            NSString * qrcode_h = responseObject[@"result"][@"image"][@"qrcode_h"];
            NSString * qrcode_w = responseObject[@"result"][@"image"][@"qrcode_w"];
            if (![NSString isEmptyString:imageUrl]) {
                [weakSelf.bgImageVIew sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:nil];
                [weakSelf createQRcodWithUrl:urlArray[0]qrcodeImageView:weakSelf.firestQrcodeImage];
                weakSelf.firestQrcodeImage.width = qrcode_w.floatValue/2;
                weakSelf.firestQrcodeImage.height = qrcode_h.floatValue/2;
                weakSelf.firestQrcodeImage.mj_y =UIScreenHeight - RealValue_W(qrcode_h.floatValue) -RealValue_W(24);
                weakSelf.firestQrcodeImage.centerX = self.view.centerX;
                weakSelf.bgView.hidden = YES;
            }else
            {
                weakSelf.bgView.hidden = NO;
                weakSelf.bgImageVIew.image = [UIImage imageNamed:@"bg"];
                [weakSelf createQRcodWithUrl:urlArray[0]qrcodeImageView:weakSelf.QrcodeImage];/*生成二维码*/

            }

        }else
        {
            
            [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
        }

    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];
}
- (void)returnVC
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (UIImageView *)firestQrcodeImage
{
    if (!_firestQrcodeImage) {
        
        _firestQrcodeImage = [[UIImageView alloc] initWithFrame:CGRectMake(0,UIScreenHeight - RealValue_W(252) -RealValue_W(24), RealValue_W(252), RealValue_W(252))];
        _firestQrcodeImage.centerX = self.view.centerX;
    }
    return _firestQrcodeImage;
}
- (void)invitingList
{
    InvitingListViewController * InvitingListVC = [[InvitingListViewController alloc] init];
    InvitingListVC.title = Localized(@"Invitation_record");
    [self.navigationController pushViewController:InvitingListVC animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark 长按手势弹出警告视图确认
-(void)imglongTapClick:(UILongPressGestureRecognizer*)gesture
{
    
    if(gesture.state==UIGestureRecognizerStateBegan)
    {
        
       CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:Localized(@"Asset_Sure_album") titleStr:Localized(@"Asset_Save_picture") openUrl:@"" confirm:Localized(@"transaction_OK") cancel:Localized(@"transaction_cancel")   state:2 RechargeBlock:^{
            
            // 保存图片到相册
            UIImageWriteToSavedPhotosAlbum([self captureImageFromView:self.bgImageVIew],self,@selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);
            
            
            
        }];
        
        aleartVC.animationStyle = LXASAnimationDefault;
        [aleartVC showLXAlertView];
        
        
    }
    
}
-(void)imglongTapClick1:(UILongPressGestureRecognizer*)gesture

{
    
    if(gesture.state==UIGestureRecognizerStateBegan)
    {
        
        CheckVersionAlearView * aleartVC = [[CheckVersionAlearView alloc] initWithmessage:Localized(@"Asset_Sure_album") titleStr:Localized(@"Asset_Save_picture") openUrl:@"" confirm:Localized(@"transaction_OK") cancel:Localized(@"transaction_cancel")   state:2 RechargeBlock:^{
            
            // 保存图片到相册
            UIImageWriteToSavedPhotosAlbum([self captureImageFromView:self.bgImageVIew],self,@selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);
            
            
            
        }];
        
        aleartVC.animationStyle = LXASAnimationDefault;
        [aleartVC showLXAlertView];
        
        
    }
    
    
}
-(UIImage *)captureImageFromView:(UIView *)view{
    
    UIGraphicsBeginImageContextWithOptions(self.view.frame.size,NO, 0);
    
    [[UIColor clearColor] setFill];
    
    [[UIBezierPath bezierPathWithRect:self.view.bounds] fill];
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    [self.view.layer renderInContext:ctx];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
    
}
#pragma mark 保存图片后的回调
- (void)imageSavedToPhotosAlbum:(UIImage*)image didFinishSavingWithError:  (NSError*)error contextInfo:(id)contextInfo
{
    NSString*message =@"";
    
    if(!error) {
        
        message =Localized(@"Asset_Saved_album");
        
        [EXUnit showSVProgressHUD:message];
        
    }else
        
    {
        
        message = [error description];
        
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"album_message") view:kWindow];
        
    }
    
}
- (void)createQRcodWithUrl:(NSString *)url qrcodeImageView:(UIImageView *)qrcodeImageView{
    // 1.创建过滤器
    
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    // 2.恢复默认
    
    [filter setDefaults];
    
    // 3.给过滤器添加数据(正则表达式/账号和密码)
    
    //    NSString *dataString = @"http://www.520it.com";
    
    NSData *data = [url dataUsingEncoding:NSUTF8StringEncoding];
    
    [filter setValue:data forKeyPath:@"inputMessage"];
    
    // 4.获取输出的二维码
    
    CIImage *outputImage = [filter outputImage];
    
    // 5.将CIImage转换成UIImage，并放大显示
    
    qrcodeImageView.image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:100];
    
}
/**
 
 * 根据CIImage生成指定大小的UIImage
 
 *
 
 * @param image CIImage
 
 * @param size 图片宽度
 
 */

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size

{
    
    CGRect extent = CGRectIntegral(image.extent);
    
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    
    size_t width = CGRectGetWidth(extent) * scale;
    
    size_t height = CGRectGetHeight(extent) * scale;
    
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    
    CIContext *context = [CIContext contextWithOptions:nil];
    
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    
    CGContextScaleCTM(bitmapRef, scale, scale);
    
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    
    CGContextRelease(bitmapRef);
    
    CGImageRelease(bitmapImage);
    
    return [UIImage imageWithCGImage:scaledImage];
    
}

- (IBAction)copyCode:(UIButton *)sender {
    if (![NSString isEmptyString:self.invitingCode.text]) {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = self.invitingCode.text;
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"Copy_to_paste") view:self.view];
    }
   
}
@end
